#include "STLNode.h"

void STL_Print(STLNode* phead)
{

	while (phead)
	{
		printf("%d->", phead->data);
		phead = phead->next;
	}
	printf("NULL\n");

}

STLNode* Malloc(DataType x)
{
	STLNode* temp = (STLNode*)malloc(sizeof(STLNode));
	if (temp == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	temp->data = x;
	temp->next = NULL;

	return temp;
}

void STL_PushBack(STLNode** pphead, DataType x)
{
	STLNode* temp = Malloc(x);

	if (*pphead == NULL)
	{
		*pphead = temp;
	}
	else
	{
		STLNode* cur = *pphead;
		while (cur->next != NULL)
		{
			cur = cur->next;
		}
		cur->next = temp;
	}
}

void STL_PushFront(STLNode** pphead, DataType x)
{

	STLNode* temp = Malloc(x);
	temp->next = *pphead;
	*pphead = temp;

}

void STL_PopBack(STLNode** pphead)
{
	assert(*pphead);

	STLNode* cur = *pphead;
	STLNode* temp = *pphead;
	
	if (cur->next == NULL)
	{
		free(cur);
		*pphead = NULL;
	}
	else
	{
		while (cur->next)
		{
			temp = cur;
			cur = cur->next;
		}
		free(cur);
		temp->next = NULL;
	}
	
}

void STL_PopFront(STLNode** pphead)
{
	assert(*pphead);

	STLNode* cur = *pphead;
	*pphead = (*pphead)->next;
	free(cur);

}

STLNode* STL_Find(STLNode* phead, DataType x)
{
	if (phead == NULL)
	{
		printf("NULL\n");
		return;
	}

	while (phead != NULL)
	{
		if (phead->data == x)
		{
			return phead;
		}
		phead = phead->next;
	}

	printf("Can not find\n");
	return;
}

void STL_InsertAfter(STLNode* pos, DataType x)
{

	STLNode* temp = Malloc(x);
	temp->next = pos->next;
	pos->next = temp;

}

void STL_EraseAfter(STLNode* pos)
{
	assert(pos->next);

	STLNode* cur = pos->next;
	pos->next = pos->next->next;

	free(cur);
}

void STL_Destroy(STLNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}

	STLNode* temp = *pphead;
	STLNode* cur = *pphead;
	while (temp)
	{
		cur = temp->next;
		free(temp);
		temp = cur;
	}
	*pphead = NULL;
}